<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="菜品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入菜品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dish:dish:remove']"
        >批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="statusUpdate([],1)"
        >批量启售
        </el-button>
      </el-col>
      <!--      v-hasPermi="['dish:dish:remove']"-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="statusUpdate([],0)"
        >批量停售
        </el-button>
      </el-col>
      <!--      v-hasPermi="['dish:dish:remove']"-->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dish:dish:add']"
        >新建菜品
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dishList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="菜品名称" align="center" prop="name"/>
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="菜品分类" align="center" prop="categoryId">
        <template slot-scope="scope">
          <span v-for="item in categorylist">
            <span v-if="item.id == scope.row.categoryId">{{item.name}}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="售价" align="center" prop="price">
        <template slot-scope="scope">
          <span>¥{{ scope.row.price / 100 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="售卖状态" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{ scope.row.status == 0 ? '停售' : '启售' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后操作时间" align="center" prop="updateTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dish:dish:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="statusUpdate(scope.row,[[scope.row.status == 0 ? 1 : 0]])"
            v-hasPermi="['dish:dish:edit']"
          >{{ scope.row.status == 0 ? '启售' : '停售' }}
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dish:dish:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改菜品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="菜品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入菜品名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜品分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择菜品分类">
                <el-option
                  v-for="item in categorylist"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="菜品价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入菜品价格" style="width: 225px;"/>
        </el-form-item>

        <el-form-item label="菜品图片">
          <image-upload v-model="form.image"/>
        </el-form-item>

        <el-form-item label="菜品描述" prop="description">
          <el-input type="textarea" :rows="2" v-model="form.description" placeholder="菜品描述"/>
        </el-form-item>

        <el-divider content-position="center">菜品口味关系信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddDishFlavor">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteDishFlavor">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="dishFlavorList" :row-class-name="rowDishFlavorIndex"
                  @selection-change="handleDishFlavorSelectionChange" ref="dishFlavor">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="口味名称" prop="name" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.name" @change="selectname(scope.row.index)" placeholder="请选择口味名称">
                <el-option label="温度" value="温度"></el-option>
                <el-option label="辣度" value="辣度"></el-option>
                <el-option label="甜味" value="甜味"></el-option>
                <el-option label="忌口" value="忌口"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="口味" prop="createUser" width="350">
            <template slot-scope="scope">
              <el-select v-model="scope.row.value" style="width: 320px;" multiple placeholder="请选择口味类型">
                <el-option
                  v-for="item in scope.row.flavorArry"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listDish, getDish, delDish, addDish, updateDish, updataStatus} from "@/api/dish/dish";
import {getCategorylistAll} from "../../../api/dish/dish";

export default {
  name: "Dish",
  data() {
    return {
      categorylist: [],
      testSiteId: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedDishFlavor: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 菜品管理表格数据
      dishList: [],
      // 菜品口味关系表格数据
      dishFlavorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        categoryId: null,
        price: null,
        code: null,
        image: null,
        description: null,
        status: null,
        sort: null,
        createUser: null,
        updateUser: null,
        isDeleted: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "菜品名称不能为空", trigger: "blur"}
        ],
        categoryId: [
          {required: true, message: "菜品分类不能为空", trigger: "blur"}
        ],
        price: [
          {required: true, message: "菜品价格不能为空", trigger: "blur"}
        ],
        image: [
          {required: true, message: "图片不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {

    /** 获取分类列表 */
    getCategorylist(){
      getCategorylistAll().then(resp=>{
        this.categorylist = resp.data;
      });
    },

    selectname(index){
      console.log(this.dishFlavorList[index-1]);
      if(this.dishFlavorList[index-1].name == "温度"){
        this.dishFlavorList[index-1].flavorArry = ['热饮', '常温', '去冰', '少冰'];
      }else if(this.dishFlavorList[index-1].name == "辣度"){
        this.dishFlavorList[index-1].flavorArry = ['不辣', '微辣', '中辣', '特辣'];
      }else if(this.dishFlavorList[index-1].name == "甜味"){
        this.dishFlavorList[index-1].flavorArry = ['无糖', '少糖', '半糖', '多糖'];
      }else{
        this.dishFlavorList[index-1].flavorArry = ['不要香菜', '不要蒜', '不要辣', '不要甜'];
      }
    },

    /**---------------------------------------------------------*/

    /** 修改菜品状态 */
    statusUpdate(row, status) {
      const ids = row.id || this.ids;
      const statusname = status == 1 ? '启售' : '停售';
      this.$modal.confirm('是否确认' + statusname + '【"' + ids + '"】数据项？').then(function () {
        return updataStatus(ids, status);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(statusname + "成功");
      }).catch(() => {
      });
    },
    /** 查询菜品管理列表 */
    getList() {
      this.loading = true;
      this.getCategorylist();
      listDish(this.queryParams).then(response => {
        console.log(response);
        this.dishList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        categoryId: null,
        price: null,
        code: null,
        image: null,
        description: null,
        status: 0,
        sort: null,
        createTime: null,
        updateTime: null,
        createUser: null,
        updateUser: null,
        isDeleted: null
      };
      this.dishFlavorList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getCategorylist();
      this.open = true;
      this.title = "添加菜品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getCategorylist();
      this.open = true;
      this.title = "修改菜品";
      this.reset();
      const id = row.id || this.ids
      getDish(id).then(response => {
        this.form = response.data;
        this.dishFlavorList = response.data.dishFlavorList;
        for (let i = 0; i < response.data.dishFlavorList.length; i++) {
          this.dishFlavorList[i].value = response.data.dishFlavorList[i].flavorValue;
        }
        this.open = true;
        this.title = "修改菜品";
      });
    },

    /** 口味 value 类型转换 */
    valueZhuanHuan(){
      for (var i = 0; i < this.form.dishFlavorList.length; i++){
        var str = '[';
        for (var j = 0; j < this.form.dishFlavorList[i].value.length; j++){
          str += '"'+this.form.dishFlavorList[i].value[j]+'"';
          if(j < this.form.dishFlavorList[i].value.length-1){
            str += ',';
          }else{
            str += ']';
          }
        }
        this.form.dishFlavorList[i].value = str;
      }
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.dishFlavorList = this.dishFlavorList;
          if (this.form.id != null) {
            this.valueZhuanHuan();
            updateDish(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.valueZhuanHuan();
            addDish(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除【"' + ids + '"】数据项？').then(function () {
        return delDish(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 菜品口味关系序号 */
    rowDishFlavorIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 菜品口味关系添加按钮操作 */
    handleAddDishFlavor() {
      let obj = {};
      obj.name = "";
      obj.value = "";
      obj.flavorArry = [];
      this.dishFlavorList.push(obj);
    },
    /** 菜品口味关系删除按钮操作 */
    handleDeleteDishFlavor() {
      if (this.checkedDishFlavor.length == 0) {
        this.$modal.msgError("请先选择要删除的菜品口味关系数据");
      } else {
        const dishFlavorList = this.dishFlavorList;
        const checkedDishFlavor = this.checkedDishFlavor;
        this.dishFlavorList = dishFlavorList.filter(function (item) {
          return checkedDishFlavor.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleDishFlavorSelectionChange(selection) {
      this.checkedDishFlavor = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('dish/dish/export', {
        ...this.queryParams
      }, `dish_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
